package com.wuxiaofan.intercepter;

import com.wuxiaofan.annotation.MyLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.WebRequestInterceptor;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.WebRequestHandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@Slf4j
public class MyLogInterceptor implements HandlerInterceptor {
    private static final ThreadLocal threadLocal = new ThreadLocal();

    /**
     * controller 执行之前执行的方法
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            Method method = handlerMethod.getMethod();
            MyLog myLogAnnotation = method.getAnnotation(MyLog.class);
            if(myLogAnnotation!=null){
                threadLocal.set(System.currentTimeMillis());
            }
        }
        return true;
    }

    /**
     * controller 方法执行之后执行的方法
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            Method method = handlerMethod.getMethod();
            MyLog myLogAnnotation = method.getAnnotation(MyLog.class);

            String requestURI = request.getRequestURI();

            String methodName =  method.getDeclaringClass().getName()+"." + method.getName();

            if(myLogAnnotation!=null){
                long startTime = (long) threadLocal.get();
                long time = System.currentTimeMillis()- startTime;
                log.info("接口耗时：{}",time/(1000));

                String methodDesc =  myLogAnnotation.desc();

                log.info("请求地址:{}",requestURI);
                log.info("请求方法:{}",methodName);
                log.info("请求方法描述:{}",methodDesc);
            }
        }
    }

}
